package com.caocaog.market.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.finance.entity.MkBillBase;
import com.caocaog.market.finance.entity.MkBillLineHistory;
import com.caocaog.market.finance.mapper.MkBillLineHistoryMapper;
import com.caocaog.market.finance.service.MkBillBaseService;
import com.caocaog.market.finance.service.MkBillLineHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.SystemException;
import javax.transaction.Transactional;
import java.util.List;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.finance.service.impl
 * @ClassName MkBillHistoryServiceImpl.java
 * @createTime 2021年12月03日 19:25:00
 * @Description TODO
 */
@Slf4j
@Service("mkBillLineHistoryService")
public class MkBillLineHistoryServiceImpl implements MkBillLineHistoryService {
    @Autowired
    private MkBillLineHistoryMapper billLineHistoryMapper;
    @Autowired
    private MkBillBaseService billBaseService;
    @Override
    @Transactional(rollbackOn= SystemException.class)
    public int insertBillLineAndHistory(List<MkBillBase> billList,List<MkBillLineHistory> billLineHistories) {
        try{
            int relt = billLineHistoryMapper.insertBillLineAndHistory(billLineHistories);
            if(relt<1){
                billLineHistoryMapper.deleteBillLineAndHistory(billLineHistories);
                return 0;
            }
            /**
             * 插入账单行成功之后，更新账单状态
             *      更新mk_bill_base表中的pay_status值，同时 向mk_bill_history表中插入一条新的记录
             */
            for (MkBillBase billBase:billList){
                billBaseService.updatePayStatusAndInsertHistory(billBase.getOrderNo(), MarketConstant.FINANCE_PAY_STATUS_YJS);
            }
            return relt;
        } catch (Exception e){
            billLineHistoryMapper.deleteBillLineAndHistory(billLineHistories);
            log.error("执行插入出错，删除之前插入的数据");
            log.error(e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<MkBillLineHistory> findByBillLineId(String billLineId) {

        return billLineHistoryMapper.selectList(new QueryWrapper<MkBillLineHistory>().eq("bill_line_id",billLineId).orderByDesc("create_time"));
    }

    @Override
    public IPage<MkBillLineHistory> flowRecord(Page<MkBillLineHistory> page, MkBillLineHistory billLineHistory) {
        return billLineHistoryMapper.findForHistoryPage(page,billLineHistory);
    }
}
